package com.yu.waterstation.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yu.waterstation.common.handler.ServiceException;
import com.yu.waterstation.common.util.session.SessionUtil;
import com.yu.waterstation.modules.app.mapper.AddressMapper;
import com.yu.waterstation.modules.app.mapper.TaskMapper;
import com.yu.waterstation.modules.app.pojo.Address;
import com.yu.waterstation.modules.app.pojo.Task;
import com.yu.waterstation.modules.app.service.AddressService;
import com.yu.waterstation.modules.system.pojo.dto.SysUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private AddressMapper addressMapper;

    @Resource
    private TaskMapper taskMapper;

    @Override
    public Page<Address> getAddressesByConditions(String dorm, String room, int pageNo, int pageSize)   {
        QueryWrapper<Address> wrapper = new QueryWrapper<Address>();
        if (!StringUtils.isEmpty(dorm)) {
            wrapper.eq("dorm", dorm);
            if (!StringUtils.isEmpty(room))
                wrapper.eq("room", room);
        }
        wrapper.orderByAsc("dorm", "room");
        Page<Address> page = addressMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
        for (Address address : page.getRecords()) // 查询订水状态
            address.setTaskStatus(taskMapper.selectById(address.getId()) != null);
        return page;
    }

    @Override
    public List<?> getDormList()   {
        return addressMapper.selectObjs(new QueryWrapper<Address>()
                .select("dorm")
                .groupBy("dorm").orderByAsc("dorm"));
    }

    @Override
    public List<?> getRoomsOfDorm(String dorm) throws ServiceException {
        if (StringUtils.isEmpty(dorm))
            return new ArrayList<>(0);
        return addressMapper.selectObjs(new QueryWrapper<Address>()
                .select("room")
                .eq("dorm", dorm).orderByAsc("room"));

    }

    @Transactional
    @Override
    public int addAddress(Address address)   {
        return addressMapper.insert(address);
    }

    @Transactional
    @Override
    public int deleteAddressBatchIds(List<Integer> addressIdList)   {
        return addressMapper.deleteBatchIds(addressIdList);
    }

    @Transactional
    @Override
    public int updateAddress(Address address)   {
        return addressMapper.updateById(address);
    }

    // 切换叫水状态（叫水或取消叫水）
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changeTaskStatus(Integer addressId, HttpServletRequest request) throws ServiceException {
        Address address = addressMapper.selectById(addressId);

        Task task = taskMapper.selectById(addressId);
        if (task == null) {
            if(address.getTicketNum() <= 0)
                throw ServiceException.CONST_ticket_num_is_not_enough;
            task = new Task();
            task.setAddressId(addressId);
            task.setPublisher("管理员-" + SessionUtil.getCurrentSysUserUsername(request));
            task.setTimestamp(new Date());
            taskMapper.insert(task);
        } else { // 取消叫水
            taskMapper.deleteById(addressId);
        }
    }
}
